<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      <!-- 表格 :data="数据"-->
      <el-table :data="list">
        <!-- label 列表标题  prop="属性" -->
        <el-table-column align="center" prop="name" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="state" width="200" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editObj.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '未设置' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="description" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">

            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">确定</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>

            <template v-else>
              <el-button type="text" size="mini" @click="showPermissionDialog(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="row.isEdit = true">编辑</el-button>
              <!-- 气泡确认框 -->
              <el-popconfirm
                title="确定删除该角色吗？"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>

            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" style="margin: 20px 0 ">
        <el-col :span="12">
          <el-pagination
            :current-page="params.page"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="params.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <!-- 新增角色的对话框 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" @close="close">
        <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-tooltip :content="'开关状态: ' + (form.state === 1 ? '启用' : '未启用')" placement="top">
              <el-switch
                v-model="form.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" type="textarea" />
          </el-form-item>
          <div style="display:flex; justify-content: center">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="addRole">确定</el-button>
          </div>
        </el-form>
      </el-dialog>
      <!-- 为角色分配权限 -->
      <el-dialog title="分配权限" :visible.sync="perDialog">
        <!-- show-checkbox 展示复选框  check-strictly 父子不互相关联 -->
        <el-tree
          ref="treeRef"
          node-key="id"
          :data="permissionList"
          :props="{label: 'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          :default-checked-keys="permIds"
        />
        <div style="text-align: center;">
          <el-button size="mini" @click="perDialog = false">取消</el-button>
          <el-button size="mini" type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { reqAddRole, reqAssignPers, reqDelRole, reqGetRoleDetail, reqGetRolesList, reqUpdateRole } from '@/api/role'
import { reqGetPermissionList } from '@/api/permission'
import { translateToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [], // 角色列表
      total: 0, // 总数
      params: { page: 1, pagesize: 2 },
      showDialog: false,
      // 表单数据
      form: {
        name: '', // 角色名称
        description: '', // 角色描述
        state: 0 // 启用状态
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
        description: [{ required: true, message: '请输入角色描述', trigger: 'change' }]
      },
      perDialog: false, // 控制为角色分配权限的布尔值
      permissionList: [], // 权限列表
      permIds: [], // 已有权限数组
      id: null // 记录角色id
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: { rows, total }} = await reqGetRolesList(this.params)
      rows.forEach(item => {
        item.isEdit = false
        item.editObj = {
          name: item.name,
          state: item.state,
          description: item.description
        }
      })
      this.list = rows
      this.total = total
      // vue2中单独给data中的数据做字段赋值， 需要使用this.$set的方式 (处理的对象,参数2是字段key,参数3是值)
      // this.list.forEach(item => { this.$set(item, 'isEdit', false) })
    },
    // 每页条数发生变化
    handleSizeChange(val) {
      // console.log('每页条数发生变化', val)
      this.params.pagesize = val
      this.getRolesList()
    },
    // 页码发生变化
    handleCurrentChange(val) {
      // console.log('页码发生变化', val)
      this.params.page = val
      this.getRolesList()
    },
    // 关闭并重置
    close() {
      this.showDialog = false
      this.$refs.formRef.resetFields()
    },
    // 新增角色
    addRole() {
      // 1. 预校验
      this.$refs.formRef.validate(async boo => {
        if (boo) {
          // 2. 发送请求
          await reqAddRole(this.form)
          // 3. 关闭对话框并重置
          this.close()
          // 4. 提示=略过
          // 5. 重新渲染
          this.getRolesList()
        }
      })
    },
    // 取消编辑还原编辑的数据
    cancelEdit(row) {
      row.isEdit = false
      row.editObj = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    // 更新角色
    async handleUpdate(row) {
      // 1. 判断两个输入框非空
      if (!row.editObj.name.trim()) return this.$message.warning('请输入角色名称')
      if (!row.editObj.description.trim()) return this.$message.warning('请输入角色描述')
      // 2. 准备接口发送请求
      await reqUpdateRole({ ...row.editObj, id: row.id })
      // 3. 取消编辑状态 isEdit = false
      // row.isEdit = false
      // // 4. 提示
      // // 5. 重新渲染 可以 但是没有必要 会多发一次请求 => 直接将修改过的editObj同步给row对应的name,state,description
      // row.name = row.editObj.name
      // row.state = row.editObj.state
      // row.description = row.editObj.description
      // 以上错误警告 因为携带row发送了请求 eslint觉得再去赋值row的属性可能会有问题
      Object.assign(row, {
        isEdit: false,
        name: row.editObj.name,
        state: row.editObj.state,
        description: row.editObj.description
      })
    },
    // 删除角色
    async delRole(id) {
      // 点击删除按钮展示气泡弹窗
      // 准备删除的接口
      // 点击确定后发送删除的请求
      await reqDelRole(id)
      // 如果当前页只剩一条数据了 , 需要将page页码-- ,再去发送请求
      if (this.list.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      // 重新渲染
      this.getRolesList()
    },
    // https://blog.csdn.net/monparadis/article/details/114087838?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-114087838-blog-125980817.235%5Ev28%5Epc_relevant_t0_download&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-114087838-blog-125980817.235%5Ev28%5Epc_relevant_t0_download&utm_relevant_index=1
    // 展示为角色分配权限的对话框
    async showPermissionDialog(id) {
      this.id = id // 记录角色id
      this.permIds = []
      // 1. 获取权限列表并处理成树形数据
      const { data } = await reqGetPermissionList()
      this.permissionList = translateToTreeData(data, 0)
      const { data: { permIds }} = await reqGetRoleDetail(id)
      // this.$refs.treeRef.setCheckedKeys(permIds) // 通过方法来设置
      this.permIds = permIds
      this.perDialog = true
    },
    // 为角色分配权限
    async handleSubmit() {
      console.log(this.$refs.treeRef.getCheckedKeys()) // 勾选的角色权限列表
      await reqAssignPers(this.id, this.$refs.treeRef.getCheckedKeys())
      this.perDialog = false
    }

  }
}
</script>
